package com.example.clientapp.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/10/31 17:41
 */
@Controller
public class LoginController
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private static Map<String, Object> resp;

    @Autowired
    RestTemplate restTemplate;

    @PostMapping("/login")
    public String login(String username, String password, Model model)
    {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", username);
        map.add("password", password);
        map.add("client_secret", "123");
        map.add("client_id", "admin");
        map.add("grant_type", "password");
        resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, Map.class);
        String access_token = (String) resp.get("access_token");
        String refresh_token= (String) resp.get("refresh_token");
        Integer expires_in = (Integer) resp.get("expires_in");
        log.info("【获取access_token】 access_token:{}",access_token);
        log.info("【获取token的过期时间】 expires_in:{}",expires_in);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + access_token);
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8081/admin/hello", HttpMethod.GET, httpEntity, String.class);
        model.addAttribute("msg", entity.getBody());
        return "02.html";
    }

    @RequestMapping("02.html")
    public String loginPage()
    {
        return "02";
    }
}
